<template>
  <BasicModal ref="showActionModal" :title="`代理仓库`" width="1000px" @emit-callback-fn="modalCallbackFn">
    <template #content>
      <Table ref="tableRef" class="table-container" :columns="columns" :data="loadData" :alert="false" bordered>
        <template #operator>
          <div>
            <a-button type="primary" @click="handelActionTable">
              <PlusOutlined />
              添加
            </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="table-operation">
              <a @click="handelDelete(record)">删除</a>
            </div>
          </template>
        </template>
      </Table>
    </template>
  </BasicModal>

  <BasicModal
    ref="showProxyModal"
    :title="`绑定代理仓库`"
    width="800px"
    @emit-callback-fn="confirmProxyModal"
    :confirmLoading="editProxyRepositoryLoading"
  >
    <template #content><SchemaForm ref="formRef" /></template>
  </BasicModal>
</template>

<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue';
import { createVNode } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import { PordDefaultData } from '@/enums/commonEnum';
import {
  queryArtifactToolListFun,
  queryArtifactProxyListFun,
  addArtifactProxyListFun,
  deleteArtifactToolListFun,
} from '@/api/artifactRepository';
import { useArtifactRepositoryStore } from '@/store/modules/artifactRepository';
const artifactRepositoryStore = useArtifactRepositoryStore();
const { artifactObj } = artifactRepositoryStore;

const emits = defineEmits(['handleConfirm']);
const tableRef = ref<any>(null);
const showActionModal = ref<any>(null);
const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'sourceArtifactName', title: '制品工具', align: 'center' },
  { dataIndex: 'sourceArtifactServerAddr', title: '仓库地址', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      groupArtifactUuid: artifactObj.uuid,
      artifactType: artifactObj.artifactType,
    },
  };
  const data = await getList(parameObj);
  return data;
};

//获取表格数据
const getList = async (parameObj: any) => {
  return await queryArtifactProxyListFun(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res?.records || [],
    };
    return data;
  });
};

const handelActionTable = () => {
  getSelectList();
  showProxyModal.value.showModal();
};

const handelDelete = (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode(
      'div',
      { style: 'color:black;' },
      `确定要删除“代理仓库：${record.sourceArtifactName}”这一项数据吗？`,
    ),
    async onOk() {
      await deleteArtifactToolListFun(record.proxyArtifactUuid).then(() => {
        message.success('删除成功');
        tableRef.value.refresh(true);
      });
    },
    onCancel() {},
  });
};

const modalCallbackFn = async () => {
  emits('handleConfirm');
  showActionModal.value.hideModal();
};

const onOpen = () => {
  showActionModal.value.showModal();
};

// 绑定代理仓库
const showProxyModal = ref<any>(null);
const agencyOptions = ref([]);
const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'repositoryTools',
      label: '仓库工具',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      componentProps: ({ formModel }) => {
        return {
          options: agencyOptions.value,
          onChange: (e: any, option: any) => {
            formModel.repositoryAddress = option.serverAddress;
            currentItem.value = option;
          },
          fieldNames: { label: 'artifactName', value: 'uuid' },
        };
      },
      component: 'Select',
    },
    {
      field: 'repositoryAddress',
      label: '仓库地址',
      labelWidth: 90,
      dynamicDisabled: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
  ] as FormSchema[],
});

const currentItem = ref<any>({});
const editProxyRepositoryLoading = ref<boolean>(false);
const confirmProxyModal = async () => {
  await formRef.validate();
  editProxyRepositoryLoading.value = true;
  const params = {
    groupArtifactUuid: artifactObj.uuid,
    groupInstanceRepoName: artifactObj.instanceRepositoryName,
    artifactType: artifactObj.artifactType,
    sourceArtifactUuid: currentItem.value.uuid,
    sourceArtifactCode: currentItem.value.artifactCode,
    sourceArtifactName: currentItem.value.artifactName,
    sourceArtifactServerAddr: currentItem.value.serverAddress,
    sourceInstanceRepoName: currentItem.value.instanceRepoName || '',
    sourceUserName: currentItem.value.userName,
    sourcePassword: currentItem.value.password,
  };
  await addArtifactProxyListFun(params)
    .then(() => {
      message.success('添加成功');
      tableRef.value.refresh(true);
      showProxyModal.value.hideModal();
    })
    .finally(() => {
      editProxyRepositoryLoading.value = false;
    });
};

const getSelectList = async () => {
  let data = {
    dataSource: PordDefaultData.manufacturedTool,
    artifactType: artifactObj.artifactType,
  };
  await queryArtifactToolListFun(data).then((res) => {
    agencyOptions.value = res;
  });
};

onBeforeMount(() => {
  getSelectList();
});

defineExpose({
  onOpen,
});
</script>

<style lang="less" scoped>
.table-container {
  margin-bottom: 20px;
}
</style>
